<?php

/**
 * 文件工具类
 */
namespace common\utils;

use yii;

class XFile
{
    /**
     * 返回内容页列表
     * @return array
     */
    public static function getPost()
    {
        return static::getList(Yii::getAlias('@frontend' . '/views/post/'));
    }

    /**
     * 更新目录页内容
     * @param $filename
     * @param $name
     * @param $data
     * @return bool
     */
    public static function savePost($filename, $name, $data)
    {
        $top = @file_get_contents(Yii::getAlias('@frontend' . '/views/post/include'));
        $data = DIRECTORY_SEPARATOR == '\\' ? "<!--/* @description $name */-->\r\n" . $data : "<!--/* @description $name */-->\n" . $data;
        $data = $top . $data;
        return file_put_contents(Yii::getAlias('@frontend' . '/views/post/') . $filename . '.php', $data);
    }

    /**
     * @param $filename
     * @return mixed 是否存在
     */
    public static function existsPost($filename)
    {
        $filename = $filename . '.php';
        return file_exists(Yii::getAlias('@frontend' . '/views/post/') . $filename);
    }

    /**
     * 返回内容页内容
     * @param $filename
     * @return mixed
     */
    public static function getPostContent($filename)
    {
        $description = '';
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/post/') . $filename);
        if ($contents) {
            /* 只要?><!--post-->之后的代码修改 */
            $pos = strpos($contents, '?><!--post-->');
            if ($pos) {
                $contents = substr($contents, strpos($contents, '?><!--post-->') + 14);
            }
            //获取描述
            preg_match('#<!--/\* @description (.*?) \*/-->#', $contents, $result);
            if ($result) {
                $description = $result[1];
            }
            //去掉<!--/* @description $name */-->内容
            $contents = preg_replace('#<!--/\* @description(.*?)\*/-->#', '', $contents);
        }
        return ['description' => $description, 'contents' => $contents];
    }

    /**
     * 删除内容页
     * @param $filename
     * @return bool
     */
    public static function deletePost($filename)
    {
        return static::delete(Yii::getAlias('@frontend' . '/views/post/') . $filename);
    }

    /**
     * 返回目录页列表
     * @return array
     */
    public static function getCatalog()
    {
        return static::getList(Yii::getAlias('@frontend' . '/views/catalog/'));
    }

    /**
     * 返回目录页itemView列表
     * @return array
     */
    public static function getItem()
    {
        return static::getList(Yii::getAlias('@frontend' . '/views/items/'));
    }

    /**
     * @param $filename
     * @return mixed 是否存在
     */
    public static function existsItem($filename)
    {
        $filename = $filename . '.php';
        return file_exists(Yii::getAlias('@frontend' . '/views/items/') . $filename);
    }

    /**
     * 更新目录页itemView列表
     * @param $filename
     * @param $name
     * @param $data
     * @return bool
     */
    public static function saveItem($filename, $name, $data)
    {
        $top = @file_get_contents(Yii::getAlias('@frontend' . '/views/items/include'));
        $data = DIRECTORY_SEPARATOR == '\\' ? "<!--/* @description $name */-->\r\n" . $data : "<!--/* @description $name */-->\n" . $data;
        $data = $top . $data;
        return file_put_contents(Yii::getAlias('@frontend' . '/views/items/') . $filename . '.php', $data);
    }

    /**
     * 返回目录页itemView内容
     * @param $filename
     * @return mixed
     */
    public static function getItemContent($filename)
    {
        $description = '';
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/items/') . $filename);
        if ($contents) {
            /* 只要?><!--items-->之后的代码修改 */
            $pos = strpos($contents, '?><!--items-->');
            if ($pos) {
                $contents = substr($contents, strpos($contents, '?><!--items-->') + 15);
            }
            //获取描述
            preg_match('#<!--/\* @description (.*?) \*/-->#', $contents, $result);
            if ($result) {
                $description = $result[1];
            }
            //去掉<!--/* @description $name */-->内容
            $contents = preg_replace('#<!--/\* @description(.*?)\*/-->#', '', $contents);
        }
        return ['description' => $description, 'contents' => $contents];
    }

    /**
     * 删除目录页itemView
     * @param $filename
     * @return bool
     */
    public static function deleteItem($filename)
    {
        return static::delete(Yii::getAlias('@frontend' . '/views/items/') . $filename);
    }

    /**
     * 返回目录页内容
     * @param $filename
     * @return mixed
     */
    public static function getCatalogContent($filename)
    {
        $description = '';
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/catalog/') . $filename);
        if ($contents) {
            /* 只要?><!--catalog-->之后的代码修改 */
            $pos = strpos($contents, '?><!--catalog-->');
            if ($pos) {
                $contents = substr($contents, strpos($contents, '?><!--catalog-->') + 17);
            }
            //获取描述
            preg_match('#<!--/\* @description (.*?) \*/-->#', $contents, $result);
            if ($result) {
                $description = $result[1];
            }
            //去掉<!--/* @description $name */-->内容
            $contents = preg_replace('#<!--/\* @description(.*?)\*/-->#', '', $contents);
        }
        return ['description' => $description, 'contents' => $contents];
    }

    /**
     * @param $filename
     * @return mixed 是否存在
     */
    public static function existsCatalog($filename)
    {
        $filename = $filename . '.php';
        return file_exists(Yii::getAlias('@frontend' . '/views/catalog/') . $filename);
    }

    /**
     * 更新目录页内容
     * @param $filename
     * @param $name
     * @param $data
     * @return bool
     */
    public static function saveCatalog($filename, $name, $data)
    {
        $top = @file_get_contents(Yii::getAlias('@frontend' . '/views/catalog/include'));
        $data = DIRECTORY_SEPARATOR == '\\' ? "<!--/* @description $name */-->\r\n" . $data : "<!--/* @description $name */-->\n" . $data;
        $data = $top . $data;
        return file_put_contents(Yii::getAlias('@frontend' . '/views/catalog/') . $filename . '.php', $data);
    }

    /**
     * 删除目录页
     * @param $filename
     * @return bool
     */
    public static function deleteCatalog($filename)
    {
        return static::delete(Yii::getAlias('@frontend' . '/views/catalog/') . $filename);
    }

    /**
     * 返回首页内容
     * @return mixed
     */
    public static function getHomeContent()
    {
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/site/index.php'));
        if ($contents) {
            /* 只要?><!--home-->之后的代码修改 */
            $contents = substr($contents, strpos($contents, '?><!--home-->') + 14);
        }
        return $contents;
    }

    /**
     * 更新首页内容
     * @param $data
     * @return bool
     */
    public static function saveHome($data)
    {
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/site/index.php'));
        if ($contents) {
            /* 获取?><!--home-->之前的代码 */
            $contents = substr($contents, 0, strpos($contents, '?><!--home-->') + 14);
        }
        $data = $contents . $data;
        return file_put_contents(Yii::getAlias('@frontend' . '/views/site/index.php'), $data);
    }

    /**
     * 更新母版页
     * @param $filename
     * @param $data
     * @return bool
     */
    public static function saveLayout($filename, $data)
    {
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/layouts/') . $filename);
        if ($contents) {
            /* 只要<?php $this->beginBody() ?> <?php $this->endBody() ?>之间的内容*/
            preg_match('/<\?php \$this->beginBody\(\) \?>(.*?)<\?php \$this->endBody\(\) \?>/is', $contents, $result);
            if ($result) {
                $contents = str_replace($result[1], $data, $contents);
                return file_put_contents(Yii::getAlias('@frontend' . '/views/layouts/') . $filename, $contents);
            }
        }
        return false;
    }

    /**
     * 新建母版页
     * @param $name
     * @param $description
     * @param $data
     * @return mixed
     */
    public static function createLayout($name, $description, $data)
    {
        $filename = $name . '.php';
        if (!file_exists(Yii::getAlias('@frontend' . '/views/layouts/') . $filename)) {
            $myfile = fopen(Yii::getAlias('@frontend' . '/views/layouts/') . $filename, "w");
        }
        $contentTemps = @file_get_contents(Yii::getAlias('@frontend') . '/views/layouts/template');
        $contents = str_replace('{name}', $description, $contentTemps);
        $contents = str_replace('{body}', $data, $contents);
        return file_put_contents(Yii::getAlias('@frontend' . '/views/layouts/') . $filename, $contents);
    }

    /**
     * 返回母版页内容
     * @param $filename
     * @return mixed
     */
    public static function getLayoutContent($filename)
    {
        $contents = @file_get_contents(Yii::getAlias('@frontend' . '/views/layouts/') . $filename);
        if ($contents) {
            /* 只要<?php $this->beginBody() ?> <?php $this->endBody() ?>之间的内容*/
            preg_match('/<\?php \$this->beginBody\(\) \?>(.*?)<\?php \$this->endBody\(\) \?>/is', $contents, $result);
            if ($result) {
                $contents = $result[1];
            }
        }
        return $contents;
    }

    /**
     * 返回母版页列表
     * @return array
     */
    public static function getLayout()
    {
        return static::getList(Yii::getAlias('@frontend' . '/views/layouts/'));
    }

    /**
     * 删除母版页
     * @param $filename
     * @return bool
     */
    public static function deleteLayout($filename)
    {
        return static::delete(Yii::getAlias('@frontend' . '/views/layouts/') . $filename);
    }

    /**
     * 获取目录下的php文件
     * @param $path
     * @param array $ext
     * @return array|null
     */
    public static function getList($path, $ext = ['php'])
    {
        if (!file_exists($path)) {
            return null;
        }
        $file_list = [];
        if ($handle = opendir($path)) {
            $i = 0;
            while (false !== ($filename = readdir($handle))) {
                $file_ext = strtolower(pathinfo($path . $filename, PATHINFO_EXTENSION));
                $file_basename = basename($path . $filename, '.php');
                if (in_array($file_ext, $ext)) {
                    $file_list[$i]['name'] = '';
                    $contents = @file_get_contents($path . $filename);
                    if ($contents) {
                        preg_match('#/\* @description (.+?) \*/#', $contents, $result);
                        if ($result) {
                            $file_list[$i]['name'] = $result[1];
                        }
                    }
                    $file_list[$i]['filename'] = $filename;
                    $file_list[$i]['basename'] = $file_basename;
                    $file_list[$i]['ext'] = $file_ext;
                    $file_list[$i]['path'] = $path . $filename;
                    $file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($path . $filename));
                    $i++;
                }
            }
            closedir($handle);
        }
        return $file_list;
    }

    /**
     * 删除文件
     * @param $path string 物理路径
     * @return bool
     */
    public static function delete($path)
    {
        if (file_exists($path)) {
            return unlink($path);
        }
        return false;
    }

    /**
     * 删除目录及目录下所有文件或删除指定文件
     * @param str $path 待删除目录路径
     * @param bool $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
     * @return bool 返回删除状态
     */
    public static function delDirAndFile($path, $delDir = false)
    {
        $handle = opendir($path);
        if ($handle) {
            while (false !== ($item = readdir($handle))) {
                if ($item != "." && $item != "..")
                    is_dir("$path/$item") ? static::delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
            }
            closedir($handle);
            if ($delDir)
                return rmdir($path);
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return FALSE;
            }
        }
    }

    /**
     * 删除$dir目录下的目录和文件
     * @param string $dir 目录
     * @return bool
     */
    public static function delDir($dir)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    $file_ext = strtolower(pathinfo($fullpath, PATHINFO_EXTENSION));
                    if ($file_ext != 'gitignore')
                        unlink($fullpath);
                } else {
                    static::deldir($fullpath);
                }
                if (is_dir($fullpath))
                    rmdir($fullpath);
            }
        }
        closedir($dh);
        return true;
    }

    /***
     * 清空前台生成的资源文件
     * @return bool
     */
    public static function delFrontendAssets()
    {
        return static::delDir(Yii::getAlias('@frontend') . '/web/assets');
    }

    /***
     * 清空前台生成的资源文件
     * @return bool
     */
    public static function delCache()
    {
        return static::delDir(Yii::getAlias('@frontend') . '/runtime/cache');
    }

    /**
     * 单个文件上传
     * @param $file $file input的名称
     * @param string $dirext 提高扩展目录,如"goods/"
     * @return array ['error'=>'','path'=>'','name'=>'','msg'=>'']
     */
    public static function uploadOne($file, $dirext = '')
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        @set_time_limit(0);

        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
            'flash' => array('swf', 'flv'),
            'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4','mov'),
            'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        //最大文件大小
        $max_size = 1024 * 1024 * 20;

        $data = ['error' => '2', 'path' => '', 'name' => '', 'msg' => '没上文件上传'];
        $upload = yii\web\UploadedFile::getInstanceByName($file);
        if ($upload->size) {
            $ext = $upload->extension;
            if ($upload->size > $max_size) {
                return $data = ['error' => '1', 'path' => '', 'name' => '', 'msg' => '文件：' . $upload->baseName . '.' . $ext . '超出最大限制大小(' . ($max_size / 1024) . 'K).'];
            }
            $extin = false;
            foreach ($ext_arr as $et) {
                if (in_array($ext, $et)) {
                    $extin = true;
                    break;
                }
            }
            if (!$extin) {
                return $data = ['error' => '1', 'path' => '', 'name' => '', 'msg' => '文件：' . $upload->baseName . '.' . $ext . '不允许上传,该扩展名不在允许范围内.'];
            }
            $imagesizeWidth = '';
            $imagesizeHeight = '';
            if (in_array($ext, ['gif', 'jpg', 'jpeg', 'png'])) {
                $imagesize = getimagesize($upload->tempName);//图片大小
                $imagesizeWidth = $imagesize[0];
                $imagesizeHeight = $imagesize[1];
            }
//            $dir = '/uploads/' . $dirext . date('Y-m');
//            if (!is_dir(Yii::getAlias('@webroot') . $dir)) {
//                mkdir(Yii::getAlias('@webroot') . $dir,0777,true);//新建多层文件夹
//            }
            $path = '/uploads/image/' . date('Ymd') . '/' . time() . '.'.$upload->extension;
            $dir = '/uploads/image/' . date('Ymd') ;
            if (!is_dir(Yii::getAlias('@frontend/web') . $dir)) {
                mkdir(Yii::getAlias('@frontend/web') . $dir,0777,true);//新建多层文件夹
            }
            //$path = $dir . '/' . time() . rand(0, 99) . $upload->size . '_' . $imagesizeWidth . '_' . $imagesizeHeight . '_.' . $upload->extension;
            if ($upload->saveAs(Yii::getAlias('@frontend/web') . $path)) {
                //$name = explode('.', $_REQUEST['name']);
                $name=isset($_FILES[$file]['name'])?$_FILES[$file]['name']:'';
                $data = ['error' => '0', 'path' => $path, 'name' => $name, 'msg' => '上传成功'];
            } else {
                $data = ['error' => '1', 'path' => '', 'name' => '', 'msg' => $upload->error];
            }
        }
        return $data;
    }
}